import CryptoJS from 'crypto-js';

let httpUrl = new URL('https://spark-api.xf-yun.com/v3.5/chat');
let modelDomain; // V1.1-V3.5动态获取，高于以上版本手动指定
const APPID = '5fb763b6';
const API_SECRET = '27a5446b5bc9545023930aaa52ba5d03';
const API_KEY = '9830028a716aacb466888295a94056f3';

function getWebsocketUrl() {
  // console.log(httpUrl.pathname)
  // 动态获取domain信息
  switch (httpUrl.pathname) {
    case '/v1.1/chat':
      modelDomain = 'general';
      break;
    case '/v2.1/chat':
      modelDomain = 'generalv2';
      break;
    case '/v3.1/chat':
      modelDomain = 'generalv3';
      break;
    case '/v3.5/chat':
      modelDomain = 'generalv3.5';
      break;
  }

  return new Promise((resolve, reject) => {
    var apiKey = API_KEY;
    var apiSecret = API_SECRET;

    var url = 'wss://' + httpUrl.host + httpUrl.pathname;

    // console.log("我打印的" + httpUrl.host)
    // console.log("我打印的" + httpUrl.pathname)

    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = 'hmac-sha256';
    var headers = 'host date request-line';
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    resolve(url);
  });
}

export default class TTSRecorder {
  constructor({ resultCallback, statusCallback } = {}) {
    this.appId = APPID;
    this.status = 'init'; // 初始状态
    this.resultCallback = resultCallback; // 结果回调
    // 状态回调
    this.statusCallback = statusCallback;
  }

  // 修改状态
  setStatus(status) {
    this.status = status;
    this.statusCallback(this.status);
  }

  // 连接websocket
  connectWebSocket(text) {
    this.setStatus('ttsing');
    return getWebsocketUrl().then(url => {
      let ttsWS;
      if ('WebSocket' in window) {
        ttsWS = new WebSocket(url);
      } else if ('MozWebSocket' in window) {
        ttsWS = new MozWebSocket(url);
      } else {
        alert('浏览器不支持WebSocket');
        return;
      }
      this.ttsWS = ttsWS;
      ttsWS.onopen = e => {
        this.webSocketSend(text);
      };
      ttsWS.onmessage = e => {
        this.result(e.data);
      };
      ttsWS.onerror = e => {
        clearTimeout(this.playTimeout);
        this.setStatus('error');
        alert('WebSocket报错，请f12查看详情');
        console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`);
      };
      ttsWS.onclose = e => {
        console.log(e);
      };
    });
  }

  // websocket发送数据
  webSocketSend(text) {
    var params = {
      header: {
        app_id: this.appId,
        uid: 'fd3f47e4-d',
      },
      parameter: {
        chat: {
          domain: modelDomain,
          temperature: 0.5,
          max_tokens: 1024,
        },
      },
      payload: {
        message: {
          // 输入文本上下文数据
          text: text,
        },
      },
    };

    this.ttsWS.send(JSON.stringify(params));
  }

  // 开始
  start(text) {
    this.connectWebSocket(text);
  }

  // websocket接收数据的处理
  result(resultData) {
    let jsonData = JSON.parse(resultData);
    this.resultCallback(jsonData);
    // 提问失败
    if (jsonData.header.code !== 0) {
      alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
      console.error(`${jsonData.header.code}:${jsonData.header.message}`);
      return;
    }
    // 结束
    if (jsonData.header.code === 0 && jsonData.header.status === 2) {
      this.ttsWS.close();
      this.setStatus('init');
    }
  }
}
